



/**
 * 画可视域
 */
import Draw from "./Draw";
import ViewShedStage from "../../analyze/types/ViewShedStage";
import * as turf from '@turf/turf'
import Transform from '../../transform/Transform'

const DEF_STYLE = {

}

export default class DrawViewShed extends Draw {

  constructor(style) {
    super()
    this._style = {
      ...DEF_STYLE,
      ...style
    }
    this._message = '左键点击开始, 再次点击结束'
  }

  _mountEntity() {}

  _onClick(e) {
    e = this.getMouseInfo(e.position)
    let position = this._clampToGround ? e.position : e.position
    if (!position) {
      return false
    }
    let len = this._positions.length

    if (len === 0) {
      this._positions.push(position)
      this.createAnchor(position)
      this._delegate = new ViewShedStage(this._viewer, {
        viewPosition: position,
        viewDistance: 0
      })
      this._delegate._positions.push(position)
      this._floatingAnchor = this.createAnchor(position)
    }

    if (len > 1) {
      this.unbindEvent()
      this._delegate._positions.push(position)
      this._plotEvent.raiseEvent(this._delegate)
    }
    this._positions.push(position)
  }

  /**
   * 
   */
  _onMouseMove(e) {
    e = this.getMouseInfo(e.endPosition)
    this._tooltip.showAt(e.windowPosition, this._message)
    if (this._floatingAnchor) {

      let position = this._clampToGround ? e.surfacePosition : e.position
      if (!position) {
        return false
      }
      // this._floatingAnchor.position.setValue(position)

      this._positions.pop()
      this._positions.push(position)

      let startPosition = this._positions[0]
      let angle = this.computedPointAngle(startPosition, position)
      let distance = Cesium.Cartesian3.distance(startPosition, position)
      this._delegate.viewDistance = distance
      this._delegate.viewHeading = angle
    }
  }

  /**
   * 计算两点之间角度
   * @param {*} startPoint 
   * @param {*} endPoint 
   */

  computedPointAngle(startPoint, endPoint) {
    startPoint = Transform.Cartesian3ToWGS84(this._viewer, startPoint)
    startPoint = [startPoint[0], startPoint[1]]

    endPoint = Transform.Cartesian3ToWGS84(this._viewer, endPoint)
    endPoint = [endPoint[0], endPoint[1]]

    let point1 = turf.point(startPoint)
    var point2 = turf.point(endPoint)

    return turf.bearing(point1, point2)
  }

}